package thread;

import netscape.security.UserTarget;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhangxin
 * @date 2021/5/18
 */
public class InvokeThreadSafe {

    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    private volatile int i = 0;


    public synchronized void add() {
        i++;
    }

    public int getI() {
        return i;
    }

    public static void main(String[] args) throws InterruptedException, IllegalAccessException, NoSuchFieldException {
        InvokeThreadSafe invokeThreadSafe = new InvokeThreadSafe();

        int threadCount = 0;
        CountDownLatch countDownLatch = new CountDownLatch(5);
        while (threadCount < 5) {
            executorService.execute(() -> {
                int j = 0;
                try {
                    Field i = invokeThreadSafe.getClass().getDeclaredField("i");
                    i.setAccessible(true);
                    while (j++ < 10) {
                        // i.set(invokeThreadSafe, (int) i.get(invokeThreadSafe) + 1);

                        invokeThreadSafe.add();
                    }


                    countDownLatch.countDown();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            });
            threadCount++;
        }

        countDownLatch.await();
        System.out.println(invokeThreadSafe.getI());

        executorService.shutdown();
    }
}

